import dayjs from 'dayjs';

interface RentPlan {
  id?: number;
  dueDate: string; // 应收日期
  rentReceivable: number; // 应收租金
  collect: boolean; // 是否收取
  paidInTime?: string; // 实收日期
}

interface GenRentPlanParams {
  frequencyOfRentPayments: 'monthly_payment' | 'quarterly_contributions' | 'semi_annual_contributions' | 'year_payment'; // 缴租频次
  rents: number; // 租金（万元）
  startTime: string; // 开始时间
  endTime: string; // 结束时间
  transform?: boolean; // 是否需要转换万元与元
}

export function generateRentPlan({ frequencyOfRentPayments, rents, startTime, endTime, transform = false }: GenRentPlanParams): RentPlan[] {
  const plans: RentPlan[] = [];
  let currentDate = dayjs(startTime);
  const endDate = dayjs(endTime);

  const frequencyOfRentPaymentsMap = {
    monthly_payment: 1,
    quarterly_contributions: 3,
    semi_annual_contributions: 6,
    year_payment: 12
  };

  // 将万元转换为元（按年则是万元，按月则是元）
  const rentAmount = transform ? rents * 10000 : rents;

  while (currentDate.isBefore(endDate) || currentDate.isSame(endDate)) {
    // 计算下一个日期
    const nextDate = currentDate.add(frequencyOfRentPaymentsMap[frequencyOfRentPayments], 'month');

    // 如果下一个日期超出了结束日期，使用结束日期作为最后一个计划的日期
    const planDate = nextDate.isAfter(endDate) ? endDate : currentDate;

    plans.push({
      dueDate: planDate.format('YYYY-MM-DD'),
      rentReceivable: rentAmount,
      collect: false,
      paidInTime: undefined
    });

    // 如果下一个日期已经超出结束日期，退出循环
    if (nextDate.isAfter(endDate)) {
      break;
    }

    currentDate = nextDate;
  }

  return plans;
}

// 新增一个函数用于生成单条收租计划
export function generateSingleRentPlan(currentDate?: string): RentPlan {
  return {
    dueDate: currentDate ?? '',
    rentReceivable: 0,
    collect: false,
    paidInTime: undefined
  };
}
